import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Effects
import "../component" as C

Rectangle {
    id: userPageRoot
    color: "transparent"
    anchors.margins: 20
    radius: 50
    clip: true
    visible: true
    Theme { id: theme }
    FontLoader {
        id: iconFont
        source: "qrc:/assets/fontawesome-free-6.7.2-desktop/otfs/Font Awesome 6 Free-Solid-900.otf"
    }

    property alias name: inputAccount.text
    property alias password: inputPassword.text
    property alias realName: inputName.text
    property alias userPageTitle: userTitle.text
    // 单选按钮状态
    property bool yesSelected: false
    property bool noSelected: true
    property int selectedRole: 2 // 0=系统管理员, 1=管理员, 2=操作员, 3=查看员

    // 错误提示状态
    property string errorMessage: ""
    property bool showError: false
    property int rowIndex:-1

    function fillData(index, data) {
        rowIndex= index;
        inputAccount.text = data.name
        inputPassword.text = data.password
        inputName.text = data.real_name
        yesSelected = (data.status === "1" || data.status === 1)
        noSelected = !yesSelected
        selectedRole = Number.parseInt(data.permission);
        userTitle.text="修改用户"
        calendar.selectedDate = new Date(data.expiration);
    }
    function clearData(){
        rowIndex= -1;
        inputAccount.text = ""
        inputPassword.text = ""
        inputName.text = ""
        yesSelected = true
        noSelected = !yesSelected
        selectedRole = 1;
        userTitle.text="新增用户"
    }

    Rectangle {
        id: newUserCard
        anchors.fill: parent
        anchors.margins: 0
        color: "transparent"

        Item {
            id: headerArea
            anchors.top: parent.top
            anchors.left: parent.left
            anchors.right: parent.right
            height: 120

            RowLayout {
                id: headerRow
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.verticalCenter: parent.verticalCenter
                spacing: 480
                Item{
                    id: backBtn
                    width: 96
                    height: 96
                    C.ZButtonImage{
                        btnImagePressed: "qrc:/assets/back_pressed.png"
                        btnImage:"qrc:/assets/back.png"
                        onClicked: {
                            swipeView.currentIndex =0;
                            showError = false;
                        }
                    }
                }

                Label {
                    id: userTitle
                    text: "新增用户"
                    font.pixelSize: 44
                    color: "#333"
                    Layout.alignment: Qt.AlignVCenter
                    verticalAlignment: Text.AlignVCenter
                }

                Item {
                    id: saveBtn
                    width: 96
                    height: 96

                    C.ZButtonImage{
                        btnImagePressed: "qrc:/assets/save_pressed.png"
                        btnImage:"qrc:/assets/save.png"
                        onClicked: {
                            console.log("保存")
                            showError = false
                            errorMessage = ""

                            if (!inputAccount.text.trim()) {
                                errorMessage = "请输入账号"
                                showError = true
                                return
                            }

                            if (!inputPassword.text.trim()) {
                                errorMessage = "请输入密码"
                                showError = true
                                return
                            }

                            if (!inputName.text.trim()) {
                                errorMessage = "请输入姓名"
                                showError = true
                                return
                            }

                            if (rowIndex === -1){
                                var accountExists = false
                                for (var i = 0; i < userInfo.count(); i++) {
                                    var existingUser = userInfo.get(i)
                                    if (existingUser && existingUser.name === inputAccount.text.trim()) {
                                        accountExists = true
                                        break
                                    }
                                }

                                if (accountExists) {
                                    errorMessage = "账号已存在，请使用其他账号"
                                    showError = true
                                    return
                                }

                                console.log("=== 表单调试输出 ===")
                                console.log("账号:", inputAccount.text)
                                console.log("密码:", inputPassword.text)
                                console.log("姓名:", inputName.text)
                                console.log("许可:", yesSelected)
                                console.log("权限:",
                                            selectedRole === 0 ? "系统管理员" :
                                                                 selectedRole === 1 ? "管理员" :
                                                                                      selectedRole === 2 ? "操作员" :
                                                                                                           selectedRole === 3 ? "查看员" : "未知")
                                console.log("期限:", calendar.selectedDate ? calendar.selectedDate.toLocaleDateString(Qt.locale(), "yyyy-MM-dd") : "未选择")
                                console.log("====================")

                                userInfo.addRecord(inputAccount.text.trim(), inputPassword.text, inputName.text.trim(), calendar.selectedDate.toLocaleDateString(Qt.locale(), "yyyy-MM-dd"), yesSelected? "1":"0", selectedRole, userInfo.currentLogin.name)
                                userInfo.loadUser("")
                            }else{
                                var expireStr = calendar.selectedDate ? calendar.selectedDate.toLocaleDateString(Qt.locale(), "yyyy-MM-dd") : (rowData.expiration || "")
                                var newData = {
                                    name: inputAccount.text,
                                    password: inputPassword.text,
                                    real_name: inputName.text,
                                    expiration: expireStr,
                                    status: yesSelected ? "1" : "0",
                                    permission: selectedRole,
                                    update_by: userInfo.currentUser
                                }
                                console.log("id:", newData,">>",newData.name);
                                userInfo.updateRow(rowIndex, newData)
                            }

                            swipeView.currentIndex =0;
                        }
                    }
                }
            }
        }

        Flickable {
            id: scrollFlick
            anchors.top: headerArea.bottom
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            anchors.topMargin: 10
            anchors.leftMargin: 15
            anchors.rightMargin: 20
            anchors.bottomMargin: 20
            clip: true
            interactive: true
            boundsBehavior: Flickable.DragOverBounds
            pressDelay: 120
            flickableDirection: Flickable.VerticalFlick
            contentWidth: width - 40
            contentHeight: contentLayout.height
            ScrollBar.vertical: ScrollBar {
                policy: ScrollBar.AsNeeded
                visible: scrollFlick.contentHeight > scrollFlick.height && (scrollFlick.moving || scrollFlick.flicking || scrollFlick.dragging)
            }

            ColumnLayout {
                id: contentLayout
                width: scrollFlick.width - 40
                spacing: 16
                anchors.horizontalCenter: parent.horizontalCenter

                RowLayout{
                    Rectangle {
                        visible: showError
                        width: contentLayout.width
                        height: 28
                        radius: 8
                        Layout.alignment: Qt.AlignHCenter
                        Text {
                            text: errorMessage
                            color: "#C62828"
                            font.pixelSize: 20
                            anchors.centerIn: parent
                            wrapMode: Text.WordWrap
                        }
                    }
                }

                ColumnLayout {
                    spacing: 16
                    Layout.alignment: Qt.AlignHCenter
                    Label {
                        text: "账号"
                        font.pixelSize: 28
                        color: "#333"
                        Layout.alignment: Qt.AlignLeft
                    }
                    EInput {
                        id: inputAccount
                        width: 740
                        height: 70
                        Layout.alignment: Qt.AlignHCenter
                        placeholderText: "请输入账号"
                        backgroundImageSource: "qrc:/assets/input.png"
                    }
                }

                ColumnLayout {
                    spacing: 16
                    Layout.alignment: Qt.AlignHCenter
                    Label {
                        text: "密码"
                        color: "#333"
                        font.pixelSize: 28
                        Layout.alignment: Qt.AlignLeft
                    }
                    EInput {
                        id: inputPassword
                        width: 740
                        height: 70
                        Layout.alignment: Qt.AlignHCenter
                        passwordField: true
                        placeholderText: "请输入密码"
                        backgroundImageSource: "qrc:/assets/input.png"
                    }
                }

                ColumnLayout {
                    spacing: 16
                    Layout.alignment: Qt.AlignHCenter
                    Label {
                        text: "姓名"
                        color: "#333"
                        font.pixelSize: 28
                        Layout.alignment: Qt.AlignLeft
                    }
                    EInput {
                        id: inputName
                        width: 740
                        height: 70
                        Layout.alignment: Qt.AlignHCenter
                        placeholderText: "请输入姓名"
                        backgroundImageSource: "qrc:/assets/input.png"
                    }
                }

                ColumnLayout {
                    spacing: 16
                    Layout.alignment: Qt.AlignHCenter
                    Label {
                        text: "期限"
                        color: "#333"
                        font.pixelSize: 28
                        Layout.alignment: Qt.AlignLeft
                    }
                    Item{
                        width:740
                        Layout.alignment: Qt.AlignHCenter
                        ECalendar {
                            id: calendar
                            Layout.preferredWidth: 160
                            Layout.preferredHeight: 60
                            radius: 8
                        }
                    }
                }

                ColumnLayout {
                    Layout.alignment: Qt.AlignHCenter
                    Layout.preferredWidth: 740
                    Layout.topMargin: 32
                    spacing: 12
                    Label {
                        text: "许可"
                        color: "#333"
                        font.pixelSize: 28
                        Layout.alignment: Qt.AlignLeft
                    }
                    RowLayout {
                        spacing: 108
                        width: 740
                        Layout.alignment: Qt.AlignLeft
                        Item {
                            width: yesRow.implicitWidth
                            height: yesRow.implicitHeight
                            RowLayout {
                                id: yesRow
                                spacing: 12
                                Rectangle {
                                    width: 36
                                    height: 36
                                    radius: 18
                                    border.width: 2
                                    border.color: "#ddd"
                                    color: "transparent"
                                    Rectangle { width: 28; height: 28; radius: 14; color: yesSelected ? "#4CAF50" : "transparent"; anchors.centerIn: parent }
                                }
                                Image {
                                    source: "qrc:/assets/slices/license_yes_backup.png"
                                    width: 160
                                    height: 60
                                    fillMode: Image.PreserveAspectFit
                                    smooth: true
                                    mipmap: true
                                }
                            }
                            MouseArea { anchors.fill: parent; onClicked: { yesSelected = true; noSelected = false } }
                        }
                        Item {
                            width: noRow.implicitWidth
                            height: noRow.implicitHeight
                            RowLayout {
                                id: noRow
                                spacing: 12
                                Rectangle {
                                    width: 36
                                    height: 36
                                    radius: 18
                                    border.width: 2
                                    border.color: "#ddd"
                                    color: "transparent"
                                    Rectangle { width: 28; height: 28; radius: 14; color: noSelected ? "#F44336" : "transparent"; anchors.centerIn: parent }
                                }
                                Image {
                                    source: "qrc:/assets/slices/license_no_backup.png"
                                    width: 160
                                    height: 60
                                    fillMode: Image.PreserveAspectFit
                                    smooth: true
                                    mipmap: true
                                }
                            }
                            MouseArea { anchors.fill: parent; onClicked: { yesSelected = false; noSelected = true } }
                        }
                    }
                }

                ColumnLayout {
                    spacing: 16
                    Layout.alignment: Qt.AlignHCenter
                    Label {
                        text: "权限"
                        color: "#333"
                        font.pixelSize: 28
                        Layout.alignment: Qt.AlignLeft
                    }
                    RowLayout {
                        Layout.alignment: Qt.AlignHCenter
                        width: 740
                        spacing: 36
                        Repeater {
                            model: [
                                { num: 1, label: "操作员" },
                                { num: 2, label: "QA" },
                                { num: 3, label: "系统员" },
                                { num: 4, label: "管理员" }
                            ]
                            Rectangle {
                                width: 160
                                height: 140
                                radius: 12
                                color: "#FFFFFF"
                                border.width: 2
                                clip: true
                                border.color: (selectedRole === index) ? theme.focusColor : "#E6EDF7"
                                layer.enabled: true
                                layer.effect: MultiEffect {
                                    shadowEnabled: true
                                    shadowColor: "#00000022"
                                    shadowBlur: 20
                                    shadowHorizontalOffset: 0
                                    shadowVerticalOffset: 2
                                }
                                Rectangle {
                                    visible: selectedRole === index
                                    anchors.fill: parent
                                    anchors.margins: 1
                                    radius: 12
                                    color: "#D8ECFF"
                                    opacity: 1
                                }
                                Column {
                                    anchors.centerIn: parent
                                    spacing: 10
                                    Text {
                                        text: modelData.num.toString()
                                        font.pixelSize: 26
                                        font.bold: true
                                        color: (selectedRole === index) ? theme.focusColor : "#2E394C"
                                        horizontalAlignment: Text.AlignHCenter
                                        width: parent.width
                                    }
                                    Rectangle { width: 100; height: 2; color: "#E6EDF7"; anchors.horizontalCenter: parent.horizontalCenter }
                                    Text {
                                        text: modelData.label
                                        font.pixelSize: 20
                                        color: (selectedRole === index) ? theme.focusColor : "#2E394C"
                                        horizontalAlignment: Text.AlignHCenter
                                        width: parent.width
                                    }
                                }
                                Rectangle {
                                    visible: selectedRole === index
                                    width: 45
                                    height: 45
                                    anchors.top: parent.top
                                    anchors.right: parent.right
                                    topLeftRadius: 2
                                    topRightRadius: 18
                                    bottomLeftRadius: 60
                                    bottomRightRadius: 2
                                    anchors.topMargin: -0.49
                                    anchors.rightMargin: -0.49
                                    color: theme.focusColor
                                    Text {
                                        text: "\uf00c"
                                        font.family: iconFont.name
                                        color: "white"
                                        font.pixelSize: 18
                                        anchors.centerIn: parent
                                    }
                                }
                                MouseArea {
                                    anchors.fill: parent
                                    cursorShape: Qt.PointingHandCursor
                                    onClicked: selectedRole = index
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
